<script setup lang="ts">
import * as L from 'leaflet/dist/leaflet.js';
import 'leaflet/dist/leaflet.css';
import { message } from '@/utils/message';
// import "font-awesome/css/font-awesome.min.css"
import "@/assets/ali-icon/iconfont.css"
import '@/plugins/leaflet/leaflet-beautify-marker-icon.js'
import '@/plugins/leaflet/leaflet-beautify-marker-icon.css'
import { getImageInfo } from '@/utils/functions'
import { nextTick, onBeforeMount, onMounted, onUnmounted, reactive, ref, shallowRef } from "vue";
import { ICON_TYPE_Map } from '@/constant/index'
import { isArray } from "@pureadmin/utils";
import { useDark } from "../../views/welcome/utils";
import { useMarker } from "./marker"
import nullimg from "@/assets/screenimg/deviceinfo.png"
const { isDark } = useDark();

const props = defineProps({
  /*是否可编辑*/
  editAble: {
    type: Boolean,
    default: true
  },
  /*是否可以选中，选中后标点变色*/
  selectedAble: {
    type: Boolean,
    default: false
  },
  /*选中后的颜色*/
  selectedColor: {
    type: String,
    default: "#4ADE80"
  },
  /** 背景图片 */
  bgImg: {
    type: String,
    default: "https://img1s.zhuzhai.com/drawing/2019/09/06/5d71c0cd979d2.jpg"
  },
  /** 图标数组 */
  /*图纸其余标点*/
  markerArr: {
    type: Array<any>,
    default: () => []
  },
  /** 标记点 字体图标 https://fontawesome.dashgame.com/
   * 使用阿里云图标参考阿里云使用方法 */
  iconUrl: {
    type: String,
    // default: Camera1
    default: ICON_TYPE_Map.point
  },
  /** 标记点 颜色 */
  iconColor: {
    type: String,
    default: 'red'
  },
  /** 可编辑图标数量 */
  maxEditMarkerNum: {
    type: Number,
    default: 1
  },
  /** 新增与可编辑图标列表 */
  changeMarker: {
    type: Array<any>,
    default: () => []
  },
  /** 是否显示弹窗 */
  isShowPopup: {
    type: Boolean,
    default: true
  },
})


/**
 * markerAdd 添加标记点事件
 * markerClick 点击标记点事件
 * markerRemove 删除标记点事件
 * markerMouseover 鼠标移入标记点事件
 */
const emits = defineEmits(['update:changeMarker', 'markerAdd', 'markerClick', 'markerRemove', 'markerMouseover'])

const { onMarkerSelect, getIcon, defaultSelectedColor } = useMarker()

const popupContentRef = ref()
// const fixedPoints = ref([])  // onMounted初始化图标实例
const changePoints = ref([])  // 可改变图标实例（新增和可编辑图例）
const mapState = reactive({
  showPop: false,
  width: 0,
  height: 0,
  currentHoverMarker: null,
  loading:false,
  loadImgErr: false,
  errMsg:""
})
const containerRef = ref()
//map对象 不能使用 ref
let map = null, imageOverlay = null
const container = ref("")
onBeforeMount(() => {
  container.value = "container" + Math.ceil(Math.random() * 100)
})

onMounted(() => {
  init(props.bgImg)
})

onUnmounted(() => {
  if (map) {
    map.remove()
  }
})

async function init(img){
  if(map) {
    map.remove()
  }
  mapState.loading = true
  mapState.loadImgErr = false
  getImageInfo(img).then(res => {
    mapState.width = res.width
    mapState.height = res.height
    nextTick(() => {
      initMap().then(res => {
        setImageLayer(img)
      })
    })
  }).catch(err => {
    mapState.loadImgErr = true
    mapState.errMsg = img ? '图片加载失败' : '暂无图纸信息'
     console.log('图片加载失败', mapState);

  }).finally(() => {
    mapState.loading = false
  })
  if(props.changeMarker.length > 0){
    emits('update:changeMarker', props.changeMarker)
  }
}
//初始化地图
const initMap = async () => {
  const rec = containerRef.value.getBoundingClientRect()
  let scale = Math.min(rec.width / mapState.width, rec.height / mapState.height)

  map = L.map(container.value, {
    /*maxZoom: 4,
    minZoom: -4,
    zoom: scale,
    zoomDelta: 0.1,
    zoomControl: false,
    attributionControl: false,
    doubleClickZoom: false,
    wheelPxPerZoomLevel: 200,
    crs: L.CRS.Simple,*/
    maxZoom: 20,
    zoom: 0,
    minZoom: -5,
    zoomDelta: 0.1,
    zoomControl: false,
    attributionControl: false,
    doubleClickZoom: false,
    wheelPxPerZoomLevel: 200,
    zoomSnap:0,
    crs: L.CRS.Simple
  })
}

//设置地图图片图层
const setImageLayer = async (img) => {
  // var bounds = [[0, 0], [mapState.height * 0.8, mapState.width * 0.8]]
  const bounds = [[0, 0], [mapState.height, mapState.width]]
  const imageLayer = L.imageOverlay(img, bounds, {
    interactive: true,
  }).addTo(map);
  imageOverlay = imageLayer
  map.fitBounds(bounds);

  imageLayer.on('click', (e) => {
    if (!props.editAble) {
      return
    }
    if (changePoints.value.length < props.maxEditMarkerNum) {
      let marker = addMarker(e.latlng.lat, e.latlng.lng)
      changePoints.value.push(marker)
      emits('update:changeMarker', parseMarker(changePoints.value))
    } else if (props.maxEditMarkerNum == 1) {
      if (changePoints.value[0]) {
        changePoints.value[0].setLatLng(L.latLng(e.latlng.lat, e.latlng.lng))
        emits('update:changeMarker', parseMarker(changePoints.value))
      }
    } else {
      message('最多添加' + props.maxEditMarkerNum + '个标记')
    }
  });
  initFixedMarkerArr(props.markerArr)
  initEditMarkerArr(props.changeMarker)
}

const addMarker = (lat, lng, iconUrl = props.iconUrl, interactive = true, markerItem = {}, color = props.iconColor) => {
  const sol = L.latLng(lat, lng); // x,y 相反

  const myIcon = getIcon(iconUrl, color)
  const marker = L.marker(sol, {
    draggable: interactive,
    autoPan: true,
    riseOnHover: true,
    icon: myIcon,
  });
  //摄像头选项信息
  Object.assign(marker.options, { markerItem: markerItem })

  marker.on('click', (e) => {
    if (props.selectedAble && !props.editAble) {
      onMarkerSelect(marker, props.selectedColor)
    }
    emits('markerClick', parseMarker(marker))
  })
  marker.on('add', (e) => {
    emits('markerAdd', e)
  })
  marker.on('dragend', (e) => {
    console.log("1",e);

    emits('update:changeMarker', parseMarker(changePoints.value))
  })
  marker.on('remove', (e) => {
    const i = changePoints.value.indexOf(marker)
    console.log("2",e);

    if (i !== -1) {
      console.log("3",e);

      changePoints.value.splice(i, 1)
      emits('update:changeMarker', parseMarker(changePoints.value))
    }
  })
  marker.on('dblclick', (e) => {
    if (marker.options.draggable) {
      marker.removeFrom(map)
    }
  })
  marker.on('mouseover', (e) => {
    props.isShowPopup && showMarkerPop(marker)
    emits('markerMouseover', marker)
  })
  marker.addTo(map)
  return marker
}

/*图纸标点初始化*/
const initFixedMarkerArr = async (markerArr) => {
  /*图纸不可编辑标点*/
  if (isArray(markerArr)) {
    markerArr.forEach((item) => {
      // fixedPoints.value.push(addMarker(item.lat, item.lng, item.iconUrl, false, item, defaultSelectedColor)).
      if (item.lat !== '' && item.lng !== '') {
        addMarker(item.lat, item.lng, item.iconUrl, false, item, defaultSelectedColor)
      }
    })
  }
}

/*可编辑*/
const initEditMarkerArr = async (markerArr) => {
  /*编辑中的标点*/
  if (isArray(markerArr)) {
    markerArr.forEach((item) => {
      if (item.lat !== '' && item.lng !== '') {
        changePoints.value.push(addMarker(item.lat, item.lng, item.iconUrl, true))
      }
    })
  }

}

const parseMarker = (markerArr: any[] | any) => {
  if (isArray(markerArr)) {
    let res = []
    markerArr.forEach((item) => {
      res.push({
        lat: item.getLatLng().lat,
        lng: item.getLatLng().lng,
        iconUrl: item.getIcon().options.icon,
      })
    })
    return res
  } else {
    return [{
      lat: markerArr.getLatLng().lat,
      lng: markerArr.getLatLng().lng,
      iconUrl: markerArr.getIcon().options.icon,
      markerItem: markerArr.options.markerItem
    }]
  }
}

//显示pop弹窗
const showMarkerPop = (marker) => {
  if (!props.isShowPopup) return
  mapState.currentHoverMarker = marker
  mapState.showPop = true
  nextTick(() => {
    marker.bindPopup(popupContentRef.value, {
      closeOnClick: false,
      closeButton: false,
      offset: [1, -6]
    }) // 绑定pop弹出层
      .openPopup(); // 打开pop弹出层
  })
}


//切换图片
const changeImgLayer = async (imageUrl) => {
  // imageOverlay.setUrl(imageUrl)
  init(imageUrl)
}

/*设置图纸标点*/
const setFixedMarkers = async (markerArr: any[]) => {
  initFixedMarkerArr(markerArr)
}

defineExpose({
  changeImgLayer,
  setFixedMarkers
})
</script>

<template>
  <div class="w-full h-full click-map-maker" v-loading="mapState.loading">
    <div :id="container" ref="containerRef" class="size-full xxx" :class="isDark ? '!bg-[#1b1e2e]' : ''" v-if="!mapState.loadImgErr"></div>
    <div v-else class="w-full h-full flex-c">
      <el-empty :description="mapState.errMsg"  :imageSize="120"  :image="nullimg"></el-empty>
    </div>
    <div ref="popupContentRef" v-show="isShowPopup && mapState.showPop">
      <slot :data="mapState?.currentHoverMarker?.options?.markerItem?.info">
        <el-text v-if="mapState.currentHoverMarker">
          {{ mapState.currentHoverMarker.options.markerItem.monitorName ?? '' }}
        </el-text>
      </slot>
    </div>
  </div>
</template>

<style lang="scss" >


.beautify-marker {
  .iconfont {
    font-size: 20px !important;
  }
}

.click-map-maker {
  .leaflet-pane {
    z-index: 1;
  }
}
</style>
// .xxx{
//   background: #000;
// }
